<template>
	<view class="page">
		<view class="page-mes">
			<view v-for="item in messageList">{{item}}</view>
		</view>
		<view class="tool">
			<uni-easyinput v-model="content" @confirm="sendMsg" placeholder="请输入消息" />
		</view>
	</view>
</template>
 
<script setup>
	import { ref, onMounted, onUnmounted } from 'vue';
	import WebSocketService from '@/utils/websocket';
	import store from '@/store' 
	
	const messageList = ref([])
	const content = ref([])
	
	let ws = null; // WebSocket 实例
	
	// 连接 WebSocket
	onMounted(() => {
	  ws = new WebSocketService('ws://localhost:8080/websocket'); // 替换为你的 WebSocket URL
	  ws.connect();
	
	  // 注册事件监听器
	  ws.on('open', () => {
	    console.log('WebSocket 已连接');
	  });
	
	  ws.on('message', (message) => {
		console.log("接收消息：", message)
	    messageList.value.push(message) // 接收到消息时更新视图
		content.value = ""
	  });
	
	  ws.on('error', (error) => {
	    console.error('WebSocket 错误:', error);
	  });
	
	  ws.on('close', () => {
	    console.log('WebSocket 连接关闭');
	  });
	});
	
	// 发送消息
	const sendMsg = () => {
		ws.sendMessage(content.value);
	};
	
	// 清理 WebSocket 连接
	onUnmounted(() => {
	  if (ws) {
	    ws.close();
	  }
	});
	
	// onclose(() => {
	// 	console.log("onclose---")
	// })
</script>
 
<style lang="scss" scoped>
	.page {
		height: 1000rpx;
		display: flex;
		flex-direction: column;
		.page-mes {
			height: 900rpx;
			background-color: white;
			overflow-y: auto;
		}
		
		.tool {
			display: flex;
			align-items: center;
			justify-content: center;
			height: 100rpx;
			// background-color: cyan;
		}
		
	}
</style>